package com.rdk.service.impl;


import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.rdk.constant.StrConstant;
import com.rdk.dao.TShareMessageMapper;
import com.rdk.entity.ShareInteract;
import com.rdk.entity.TShareMessage;
import com.rdk.entity.TUser;
import com.rdk.service.TShareMessageService;
import com.rdk.service.TShareService;
import com.rdk.service.TUserService;
import com.rdk.utils.BusinessException;
import com.rdk.utils.CommonUtil;
import com.rdk.utils.ContentUtil;
import com.rdk.utils.LogUtil;
import com.rdk.utils.RelativeDateFormat;
import com.rdk.utils.StringUtil;

@Service
public class TShareMessageServiceImpl extends BaseServiceImpl<TShareMessage>  implements TShareMessageService {

	@Autowired
	private TShareMessageMapper mapper;
	
	@Autowired
	private TUserService userService;
	
	@Autowired
	private TShareService shareService;

    public int getUnreadMessageCount(String userId) {
        return mapper.getUnreadMessageCount(userId);
    }
    
    /**
     * 查询互动信息
     * 
     * @param loginUserId
     * @param shareId
     * @return
     */
    public ShareInteract findShareInteract(String loginUserId, String shareId) {
        ShareInteract interact = new ShareInteract();
        JSONArray forwards = new JSONArray(), comments = new JSONArray(), likes = new JSONArray();
        // Map<String, String> tmpMap = new HashMap<String, String>();//
        // 保存评论和用户的对应关系
        for (TShareMessage message : mapper.selectByShareId(shareId)) { 
            JSONObject jsonObject = new JSONObject();
            /*TUser user = userService.findUserById(message.getFromUserId().getUserInfo());
            user.setName(user.getUserName());
            user.setId(user.getUserId());*/
            jsonObject.put("from", getFromUserInfo(message));
            if ("1".equals(message.getType())) {// 1、转发 2、点赞 3、评论 4、@
                if (message.getFromUserId().equals(loginUserId)) {
                    interact.setForwarded(true);
                }
                forwards.add(jsonObject);
            } else if ("2".equals(message.getType())) {
                if (message.getFromUserId().equals(loginUserId)) {
                    interact.setLiked(true);
                }
                likes.add(jsonObject);
            } else if ("3".equals(message.getType())) {
                if (message.getFromUserId().equals(loginUserId)) {
                    interact.setCommented(true);
                }
                // tmpMap.put(message.getMessageId(), message.getUserId());
                jsonObject.put("msgId", message.getMessageId());
                jsonObject.put("text", ContentUtil.parserContent(message.getContent()));
                jsonObject.put("time", RelativeDateFormat.format(message.getTime()));
                jsonObject.put("to", getToUserInfo(message));
                jsonObject.put("refer", message.getReferenceMessageId());
                comments.add(jsonObject);
            }
        }
        interact.setForwards(forwards);
        interact.setComments(comments);
        interact.setLikes(likes);
        return interact;
    }
    
    /**
     * 评论分组
     * 
     * @param comments
     */
    public void commentGroup(JSONArray comments) {
        Map<String, String> referMap = new HashMap<String, String>();
        Map<String, JSONObject> allCommentMap = new HashMap<String, JSONObject>();

        Map<String, JSONObject> groupMap = new HashMap<String, JSONObject>();

        List<JSONObject> deletes = new ArrayList<JSONObject>();

        for (int i = 0; i < comments.size(); i++) {
            JSONObject comment = comments.getJSONObject(i);
            String msgId = comment.optString("msgId");
            String fromId = comment.getJSONObject("from").getString("id");
            String toId = comment.getJSONObject("to").getString("id");

            allCommentMap.put(msgId, comment);

            String referenceMessageId = comment.optString("refer");
            if (StringUtil.isNotEmpty(referenceMessageId)) {// 是评论某人的
                if (referMap.containsKey(referenceMessageId)) {
                    referenceMessageId = referMap.get(referenceMessageId);
                }
                referMap.put(msgId, referenceMessageId);// 保存每条消息所属分组
                if (allCommentMap.containsKey(referenceMessageId)) {
                    JSONObject messageGroup = allCommentMap.get(referenceMessageId);
                    JSONArray refers = messageGroup.optJSONArray("replies");
                    if (refers == null) {
                        refers = new JSONArray();
                    }
                    refers.add(comment);
                    deletes.add(comment);
                    messageGroup.put("replies", refers);
                } else {// 这里是指回复某人，但没找到关联的评论，说明是回复的点赞和转发
                    // 先看看
                    // 以自己为单独一个组
                    String key = comment.getJSONObject("from").getString("id");
                    this.dealWithGroup(comment, key, groupMap, deletes);
                }
            } else {// 通过点击回复按钮或者最下面输入框回复发起人，那么再查询之前是否已有直接评论发起人的
                // 判断是否是第一次回复
                String key = fromId + "," + toId;
                if (fromId.equals(toId)) {// 自己评论自己的话以自己为key
                    key = fromId;
                }
                this.dealWithGroup(comment, key, groupMap, deletes);
            }

        }
        for (JSONObject jsonObject : deletes) {
            comments.remove(jsonObject);
        }
    }
    
    private void dealWithGroup(JSONObject comment, String key, Map<String, JSONObject> groupMap,
            List<JSONObject> deletes) {
        if (groupMap.containsKey(key)) {
            JSONObject messageGroup = groupMap.get(key);
            JSONArray refers = messageGroup.optJSONArray("replies");
            if (refers == null) {
                refers = new JSONArray();
            }
            refers.add(comment);
            deletes.add(comment);
            messageGroup.put("replies", refers);
        } else {// 第一次
            groupMap.put(key, comment);
        }
    }
    
    /**
     * @ * @param shareId
     * 
     * @param atUsers
     */
    public void at(String shareId, String userId, List<String> atUsers) {
        for (String userName : atUsers) {
            TUser user = userService.findUserByName(userName);
            if (user != null && !userId.equals(user.getUserId())) {
                TShareMessage shareMessage = new TShareMessage();
                shareMessage.setMessageId(getIntId());
                shareMessage.setShareId(shareId);
                shareMessage.setUserId(user.getUserId());
                shareMessage.setFromUserId(userId);
                shareMessage.setType("4");// 1、转发 2、点赞 3、评论 4、@
                shareMessage.setTime(new Date());
                shareMessage.setIsRead(false);
                mapper.insertSelective(shareMessage);
            } else {
                LogUtil.getLogger().info("user " + userName + " not found!");
            }
        }
    }
    
    /**
     * 转发
     * 
     * @param shareId
     * @param shareUserId
     * @param userId
     */
    public void forward(String shareId, String shareUserId, String userId) {
        TShareMessage shareMessage = new TShareMessage();
        shareMessage.setMessageId(getIntId());
        shareMessage.setShareId(shareId);
        shareMessage.setUserId(shareUserId);
        shareMessage.setFromUserId(userId);
        shareMessage.setType("1");// 1、转发 2、点赞 3、评论 4、@
        shareMessage.setTime(new Date());
        shareMessage.setIsRead(!shareMessage.getUserId().equals(shareMessage.getFromUserId()));
        mapper.insertSelective(shareMessage);
    }
    
    /**
     * 评论
     * 
     * @param reqBean
     */
    public JSONObject comment(String shareId, HttpServletRequest request,String userId) throws BusinessException {
        String commentTo = CommonUtil.getRequest(request, "commentTo");
        if (StringUtil.isEmpty(shareId) || StringUtil.isEmpty(commentTo)) {
            throw new BusinessException("获取分享失败");
        }
        TShareMessage shareMessage = new TShareMessage();
        shareMessage.setMessageId(getIntId());
        shareMessage.setShareId(shareId);
        shareMessage.setUserId(commentTo);
        shareMessage.setFromUserId(userId);
        if (StringUtil.isEmpty(shareMessage.getUserId())) {
            throw new BusinessException("获取参数失败");
        }
        shareMessage.setType("3");// 1、转发 2、点赞 3、评论 4、@
        shareMessage.setReferenceMessageId(request.getParameter("refer"));
        shareMessage.setContent(CommonUtil.getRequest(request, "content"));
        shareMessage.setTime(new Date());
        shareMessage.setIsRead(shareMessage.getUserId().equals(shareMessage.getFromUserId()));
        mapper.insertSelective(shareMessage);
        // @好友
        List<String> atUsers = ContentUtil.getAtUsers(shareMessage.getContent());
        at(shareMessage.getShareId(), userId, atUsers);

        if (!"1".equals(CommonUtil.getRequest(request, "group"))) {
            JSONObject message = new JSONObject();
            message.put("msgId", shareMessage.getMessageId());
            message.put("text", ContentUtil.parserContent(shareMessage.getContent()));
            message.put("to", commentTo);
            message.put("refer", shareMessage.getReferenceMessageId());
            return message;
        } else {// 分组情况下评论返回所有详情，刷新页面
			return shareService.findFeed(shareId, userId);
        }
    }
    
    
    public JSONArray findMessages(String userId, String timestamp, int offset) throws BusinessException {
        JSONArray array = new JSONArray();
        Map<String, Object> messageMap = new HashMap<String,Object>();
        messageMap.put("userId", userId);
        messageMap.put("lastQueryTime", timestamp);
        messageMap.put("offset", offset);
        messageMap.put("rows", StrConstant.PAGE_SIZE);
        List<TShareMessage> messages = mapper.selectNews(messageMap);
        List<TShareMessage> params = new ArrayList<TShareMessage>();
        Map<String, JSONObject> map = new HashMap<String, JSONObject>();
        for (TShareMessage message : messages) {
            JSONObject j = new JSONObject();
            j.put("share", shareService.getShareFeed(shareService.findShareDetail(message.getShare())));
            j.put("msgId", message.getMessageId());
            j.put("type", message.getType());
            j.put("from", getFromUserInfo(message));
            j.put("to", getToUserInfoAndAvatar(message));
            j.put("text", ContentUtil.parserContent(message.getContent()));
            j.put("created_at", RelativeDateFormat.format(message.getTime()));

            if ("3".equals(message.getType())) {// 评论
                String key = message.getShareId() + "," + message.getUserId() + "," + message.getFromUserId() + ","
                        + message.getType();
                JSONObject json = map.get(key);
                if (json == null) {
                    json = map.get(message.getShareId() + "," + message.getFromUserId() + "," + message.getUserId()
                            + "," + message.getType());
                }
                if (json == null) {
                    array.add(j);
                    map.put(key, array.getJSONObject(array.size() - 1));
                } else {
                    // 这里留着下面继续查询
                }
            } else {// 非评论的用messageId为key，其他回复可能引用该非引用
                array.add(j);
                map.put(message.getMessageId(), array.getJSONObject(array.size() - 1));
            }
            params.add(message);
        }
        if (params.size() > 0) {
            messages = mapper.selectNewsRelation(params);
            for (TShareMessage message : messages) {
                JSONObject j = new JSONObject();
                j.put("msgId", message.getMessageId());
                j.put("type", message.getType());
                j.put("from", getFromUserInfo(message));
                j.put("to", getToUserInfoAndAvatar(message));
                j.put("text", ContentUtil.parserContent(message.getContent()));
                JSONObject json = map.get(message.getShareId() + "," + message.getUserId() + ","
                        + message.getFromUserId());
                if (json == null) {
                    json = map.get(message.getShareId() + "," + message.getFromUserId() + "," + message.getUserId()
                            + "," + message.getType());
                }
                if (json == null) {
                    json = map.get(message.getShareId() + "," + message.getUserId() + "," + message.getFromUserId()
                            + "," + message.getType());
                }
                if (json == null && StringUtil.isNotEmpty(message.getReferenceMessageId())) {
                    json = map.get(message.getReferenceMessageId());
                }
                if (json == null) {
                    throw new BusinessException("获取关联消息错误");
                }
                JSONArray refers = json.optJSONArray("replies");
                if (refers == null) {
                    refers = new JSONArray();
                }
                refers.add(j);
                json.put("replies", refers);
            }
        }
        if (offset == 0) {
        	mapper.updateByUserId(userId);
        }
        return array;
    }
    
    /**
     * 赞
     * 
     * @param reqBean
     */
    public void addLike(String shareId,String userId,String commentTo) {
        TShareMessage shareMessage = new TShareMessage();
        shareMessage.setMessageId(getIntId());
        shareMessage.setShareId(shareId);
        shareMessage.setUserId(commentTo);
        shareMessage.setFromUserId(userId);
        shareMessage.setType("2");// 1、转发 2、点赞 3、评论 4、@
        shareMessage.setTime(new Date());
        shareMessage.setIsRead(shareMessage.getUserId().equals(shareMessage.getFromUserId()));
        mapper.insertSelective(shareMessage);
    }
    
    /**
     * 取消赞
     * 
     * @param shareId
     * @param userId
     */
    public void cancelLike(String shareId, String userId) {
    	Map<String, Object> map = new HashMap<String,Object>();
    	map.put("shareId", shareId);
    	map.put("userId", userId);
    	mapper.cancelLike(map);
    }
    
    @Transactional
    public void deleteComment(String messageId, String userId) throws BusinessException {
        TShareMessage shareMessage = mapper.selectByPrimaryKey(messageId);
        if (shareMessage != null && shareMessage.getFromUserId().equals(userId)) {
        	Map<String, Object> map = new HashMap<String,Object>();
        	map.put("shareId", shareMessage.getShareId());
        	map.put("messageId", messageId);
        	mapper.updateByShareId(map);
            mapper.deleteByPrimaryKey(messageId);
        } else {
            throw new BusinessException("该评论已经被删除！");
        }
    }
	
    public JSONObject getFromUserInfo(TShareMessage message) {
        JSONObject json = new JSONObject();
        json.put("id", message.getFromUserId());
        json.put("name", message.getFromUserName());
        json.put("avatar", message.getFromUserAvatar());
        return json;
    }
    
    public JSONObject getToUserInfoAndAvatar(TShareMessage message) {
        JSONObject json = new JSONObject();
        json.put("id", message.getUserId());
        json.put("name", message.getToUserName());
        json.put("avatar", message.getToUserAvatar());
        return json;
    }

    public JSONObject getToUserInfo(TShareMessage message) {
        JSONObject json = new JSONObject();
        json.put("id", message.getUserId());
        json.put("name", message.getToUserName());
        return json;
    }
}